import { defineStore } from 'pinia'
import { allRoutes } from '@/router/routes'
import { isNullOrUndef } from '@/utils/is';
import { useAccountStore } from '@/stores/account';

function hasRoles(route, roles) {
    const routeRoles = route.meta?.roles;

    if (isNullOrUndef(routeRoles))
        return true;

    // 都为空，说明不需要权限，返回 true
    if (routeRoles.length === 0 && roles.length === 0) return true;

    if (routeRoles.length === 0 || roles.length === 0) return false;

    return routeRoles.every((item) => roles.includes(item));
}

function hasPermissions(route, permissions) {
    const routePermissions = route.meta?.permissions;

    if (isNullOrUndef(routePermissions))
        return true;

    if (permissions.length === 0 && routePermissions.length === 0) return true;

    if (permissions.length === 0 || routePermissions.length === 0) return false;

    return routePermissions.every((item) => permissions.includes(item));
}

function hasPermission(route, roles, permissions) {
    return hasRoles(route, roles) && hasPermissions(route, permissions);
}

export const usePermissionStore = defineStore('permission', {
    state() {
        return {
        }
    },

    getters: {
        menus() {
            return allRoutes().filter((route) =>
                route.name && (!route.meta || !route.meta.isHidden));
        },
    },

    actions: {
        resetPermission() {
            this.$reset();
        },

        check(route, account) {
            return hasPermission(route, account.roles, account.permissions);
        },

        validateRoute(route) {
            const accountStore = useAccountStore();

            return route.name &&
                (isNullOrUndef(route.meta) || !route.meta.isHidden) &&
                this.check(route, accountStore.info);
        }
    },
})